package main

import (
	"flag"
	"fmt"
	"os"
	"runtime"
)

var log = NewMultipleBackEndLogger("ipa2s3")

func main() {
	var scanDir string

	configPath := flag.String("c", "conf.json", "config json file")
	remote := flag.String("r", "", "remote plist url")
	runAsHTTP := flag.Bool("b", false, "run as http service")

	help := flag.Bool("h", false, "show help")

	flag.Parse()

	if *help {
		fmt.Fprintf(flag.CommandLine.Output(), "Usage of %s: [options] [scan path]\n", os.Args[0])
		fmt.Println("options:")
		flag.PrintDefaults()
		return
	}

	argsCount := len(os.Args)
	scanDir = os.Args[argsCount-1]

	if argsCount <= 1 || len(scanDir) <= 0 {
		fmt.Println("missing [scan path]")
		return
	}

	runtime.GOMAXPROCS(runtime.NumCPU())

	err, conf := NewConfig(*configPath)
	if err != nil {
		log.Error(err)
		return
	}
	log.Info("config loaded from", *configPath)

	if *runAsHTTP {
		RunAsHTTPService(conf)
		return
	}

	//download remote plist mode
	if len(*remote) > 0 {
		ParseRemote(*remote, conf)
		return
	}

	generator := NewGenerator(conf)

	handler, err := generator.Scan(scanDir)
	if err != nil {
		log.Error(err)
		return
	}

	url, err := handler.UploadAll()
	if err != nil {
		log.Error(err)
		return
	}
	log.Info("upload success, ", url)

	local, err := handler.SaveToLocal()
	if err != nil {
		log.Error(err)
		return
	}
	log.Info("save to local success, ", local)
}

func ParseRemote(remote string, conf *PlistConfig) {
	generator := NewGenerator(conf)

	handler, err := generator.LoadPlistURL(remote)
	if err != nil {
		log.Error(err)
		return
	}

	err = handler.DownloadToLocal()
	if err != nil {
		log.Error(err)
		return
	}

	url, err := handler.UploadAll()
	if err != nil {
		log.Error(err)
		return
	}
	log.Info("upload success, ", url)

	log.Info("clear temp data")
	generator.Clear()
}

func RunAsHTTPService(conf *PlistConfig) {
	service := NewHTTPService(conf)
	service.Start()
}
